package com.qiantu.phone.widget;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;

import android.graphics.Canvas;

import android.graphics.Paint;
import android.graphics.RectF;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.LinearInterpolator;

import androidx.annotation.Nullable;

import com.qiantu.phone.R;
import com.qiantu.phone.app.AppApplication;
import com.rd.utils.DensityUtils;

public class CircleCountDownTimeView extends View {


    public enum CountDownMode {
        RUNNING, FAILED, SUCCESS
    }

    public interface CountDownListener{
        void onTimeout();//超时返回事件
        void onRetry();//点击重试
    }

    private int dp15, dp8;
    private int textYLocation;
    private int fontSize;
    private int width;
    private int height;
    private int centerX;//view 横坐标中心
    private int centerY;//view 纵坐标中心
    private String centerText;//中心文字
    private Paint haloPaint;//光晕画笔
    private Paint progressPaint;//进度画笔
    private TextPaint centerTextPaint;//中心文本画笔
    private Paint centerBackgroundPaint;//中心背景画笔

    private RectF haloRectF;//光晕位置
    private RectF centerBgRectF;//中心背景
    private RectF progressRectF;//进度位置

    private CountDownMode mode;

    private ValueAnimator timeAnimator;
    private float progress;
    private int countdownTime;
    private CountDownListener listener;

    public CircleCountDownTimeView(Context context) {
        super(context);
        init();
    }

    public CircleCountDownTimeView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        mode = CountDownMode.FAILED;
        centerText = getResources().getString(R.string.rebind);
        dp15 = DensityUtils.dpToPx(15);
        dp8 = DensityUtils.dpToPx(8);
        haloPaint = new Paint();
        haloPaint.setColor(AppApplication.getInstance().getThemeColor(R.attr.secondaryColor9));
        haloPaint.setStyle(Paint.Style.STROKE);
        haloPaint.setStrokeWidth(dp15);
        haloPaint.setAntiAlias(true);

        progressPaint = new Paint();
        progressPaint.setColor(AppApplication.getInstance().getThemeColor(R.attr.themeColor));
        progressPaint.setStyle(Paint.Style.STROKE);
        progressPaint.setStrokeWidth(DensityUtils.dpToPx(4));
        progressPaint.setAntiAlias(true);
        progressPaint.setStrokeCap(Paint.Cap.ROUND);
        progressPaint.setStrokeJoin(Paint.Join.ROUND);

        centerBackgroundPaint = new Paint();
        centerBackgroundPaint.setAntiAlias(true);

        centerTextPaint = new TextPaint();
        centerTextPaint.setAntiAlias(true);
        centerTextPaint.setTextAlign(Paint.Align.CENTER);

        setFocusable(true);
        setClickable(true);
        setOnClickListener(view -> {
            if(mode ==CountDownMode.FAILED){
                //只有失败才有点击事件
                centerBackgroundPaint.setColor(AppApplication.getInstance().getThemeColor(R.attr.secondaryColor5));
                if(listener!=null){
                    listener.onRetry();
                }
            }
        });
    }

    /**
     * 设置当前view的状态
     *
     * @param mode 运行中 失败 成功
     */
    public void setMode(CountDownMode mode, @Nullable String text) {
        this.mode = mode;
        switch (mode) {
            case RUNNING:
                centerBackgroundPaint.setColor(AppApplication.getInstance().getThemeColor(R.attr.deviceSolidBgColor));
                centerTextPaint.setColor(AppApplication.getInstance().getThemeColor(R.attr.secondaryColor6));
                fontSize = DensityUtils.dpToPx(36);
                centerTextPaint.setTextSize(fontSize);
                textYLocation = centerY + fontSize / 2;
                centerText = "00:10";
                break;
            case FAILED:
                centerBackgroundPaint.setColor(AppApplication.getInstance().getThemeColor(R.attr.themeColor));
                centerTextPaint.setColor(AppApplication.getInstance().getThemeColor(R.attr.textColor4));
                fontSize = DensityUtils.dpToPx(24);
                centerTextPaint.setTextSize(fontSize);
                textYLocation = centerY + fontSize / 2;
                centerText = text;
                break;
            case SUCCESS:
                centerBackgroundPaint.setColor(AppApplication.getInstance().getThemeColor(R.attr.deviceSolidBgColor));
                centerTextPaint.setColor(AppApplication.getInstance().getThemeColor(R.attr.secondaryColor6));
                fontSize = DensityUtils.dpToPx(24);
                centerTextPaint.setTextSize(fontSize);
                textYLocation = centerY + fontSize / 2;
                progress = 360;
                centerText = text;
                break;
        }
        invalidate();
    }

    public CountDownMode getMode() {
        return mode;
    }

    public void setCountdownTime(int countdownTime) {
        this.countdownTime = countdownTime;
    }

    public void setListener(CountDownListener listener) {
        this.listener = listener;
    }

    /**
     * 开始执行动画
     *
     * @param timeoutFailedText 超时错误文本
     */
    public void startAnimator(String timeoutFailedText) {
        if (mode != CountDownMode.RUNNING)
            return;

        if (timeAnimator == null) {
            timeAnimator = ValueAnimator.ofFloat(countdownTime, 0f);
            timeAnimator.setDuration(1000L * countdownTime);
            timeAnimator.setInterpolator(new LinearInterpolator());
            timeAnimator.addUpdateListener(valueAnimator -> {
                float value = (float) valueAnimator.getAnimatedValue();
                progress = value * (360f/countdownTime);//进度条 360除于倒计数得到块大小 把当前时间乘于块得到进度条
                centerText = String.format(value >= 10 ? "00:%d" : "00:0%d", (int)value);//没有10秒需要前面加0
                invalidate();
            });
            timeAnimator.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    super.onAnimationEnd(animation);
                    setMode(CountDownMode.FAILED, timeoutFailedText);//时间结束还没关掉就手动跳失败
                    if(listener!=null){
                        listener.onTimeout();
                    }
                }
            });
            timeAnimator.start();
        } else {
            timeAnimator.start();
        }
    }

    /**
     * 手动结束动画
     *
     * @param success 结束原因 是成功了还是失败了
     * @param text    结束文本
     */
    public void stopAnimator(boolean success, @Nullable String text) {
        /*
            if (mode != CountDownMode.RUNNING)
                return;
        */

        if (timeAnimator == null)
            return;

        if (timeAnimator.isRunning()){
            timeAnimator.pause();
        }
        setMode(success ? CountDownMode.SUCCESS : CountDownMode.FAILED, text != null ? text : centerText);
    }

    @Override
    public void draw(Canvas canvas) {
        super.draw(canvas);
        canvas.drawRoundRect(haloRectF, width, height, haloPaint);
        canvas.drawRoundRect(centerBgRectF, width, height, centerBackgroundPaint);
        canvas.drawArc(progressRectF, 0, progress, false, progressPaint);
        canvas.drawText(centerText, centerX, textYLocation, centerTextPaint);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        width = getMeasuredWidth();
        height = getMeasuredHeight();
        height = width = Math.min(width, height);//保证宽高一致
        setMeasuredDimension(width, height);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        centerX = width / 2;
        centerY = height / 2;
        haloRectF = new RectF(dp8, dp8, width - dp8, height - dp8);
        centerBgRectF = new RectF(dp15, dp15, width - dp15, height - dp15);
        progressRectF = new RectF(dp15, dp15, width - dp15, height - dp15);
        setMode(mode, centerText);
    }
}
